<!--知识图谱-->


<template>
  <div id="graph" ref="chartDom" style="width: 100%; height: 600px;"></div>
</template>

<script>
import echarts from 'echarts'; // ✅ 改为 v4 的默认引入方式
import { getGraphData } from "@/api/job";

export default {
  name: 'BaseBarChart',
  data() {
    return {
      chart: null,
      nodes: [],
      edges: []
    };
  },
  async mounted() {
    await this.initChart();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    async initChart() {
      try {
        const response = await getGraphData();
        if (response.data?.nodes && response.data?.edges) {
          this.nodes = response.data.nodes;
          this.edges = response.data.edges;
          this.renderGraph();
        }
      } catch (error) {
        console.error('图表初始化失败:', error);
      }
    },

    renderGraph() {
      const nodeIds = new Set();
      const formattedNodes = this.nodes.map(node => {
        const id = String(node.id || Math.random().toString(36).substr(2, 9));
        if (nodeIds.has(id)) {
          console.warn(`重复的节点ID: ${id}`);
        }
        nodeIds.add(id);

        return {
          id,
          name: node.name || node.label || id,
          category: node.category || 'default',
          symbolSize: node.scores ? 20 + Math.log(node.scores + 1) * 20 : 30,
          itemStyle: {
            color: this.getCategoryColor(node.category)
          },
          explanation: node.explanation // ✅ 保留 tooltip 信息
        };
      });

      const formattedEdges = this.edges
          .filter(edge => {
            const valid = nodeIds.has(String(edge.source)) && nodeIds.has(String(edge.target));
            if (!valid) {
              console.warn(`无效的边: ${edge.source} -> ${edge.target}`);
            }
            return valid;
          })
          .map(edge => ({
            source: String(edge.source),
            target: String(edge.target),
            label: edge.label || '',
            value: edge.label || '',
            lineStyle: {
              width: 1.5,
              curveness: 0.2
            }
          }));

      this.chart = echarts.init(this.$refs.chartDom);
      this.chart.setOption({

        tooltip: {
          formatter: params => {
            // if (params.dataType === 'edge') return '';
            if (params.dataType === 'node') {
              return `
                <div style="font-weight:bold">${params.name}</div>
                <div>分类: ${params.data.category}</div>
                ${params.data.explanation ? `<div>说明: ${params.data.explanation}</div>` : ''}
              `;
            }
            return `关系: ${params.data.label}`;
          }
        },
        legend: [{
          data: this.generateCategories(formattedNodes).map(c => c.name),
          bottom: 10
        }],
        series: [{
          type: 'graph',
          layout: 'force',
          draggable: true, // ✅ 确保此选项为 true（默认就是 true）
          force: {
            repulsion: 200,   // ✅ 增大节点间的斥力（默认 50）
            edgeLength: 130,  // ✅ 增大边的理想长度（默认 30）
            gravity: 0.05,    // ✅ 减小重力（默认 0.1，值越小节点越分散）
            friction: 0.4,     // ✅ 摩擦系数（0-1，默认 0.6，越小拖动越灵敏）
          },
          data: formattedNodes,
          links: formattedEdges,
          categories: this.generateCategories(formattedNodes),
          label: {
            show: true,
            position: 'right'
          },
          edgeLabel: {
            show: false, // ✅ 关键修改：关闭边上的标签显示
            formatter: '{c}'
          },
          emphasis: {
            focus: 'adjacency',
            label: {
              show: true
            }
          }
        }]
      });
    },

    getCategoryColor(category) {
      const colors = [
        '#c23531','#7f8cae','#61a0a8',
        '#d48265','#91c7ae','#749f83',
        '#ca8622','#bda29a','#6e7074'
      ];
      const index = Math.abs(
          Array.from(category || '').reduce(
              (sum, char) => sum + char.charCodeAt(0), 0
          ) % colors.length
      );
      return colors[index];
    },

    generateCategories(nodes) {
      const categories = [...new Set(nodes.map(n => n.category))];
      return categories.map(name => ({ name }));
    },

    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  }
};
</script>
